package org.ediba.siri.web.rest;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ediba.siri.core.request.domain.RequestAttachment;
import org.ediba.siri.core.request.service.RequestService;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

public class RequestAttachmentController extends Controller {

	private RequestService requestService;
	public void setRequestService(RequestService requestService){this.requestService = requestService;}
	
	public Map<String,Object> getHandler(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException{
		
		int idRequest = ServletRequestUtils.getRequiredIntParameter(request, "idRequest");
		List<RequestAttachment> _requestAttachments = new ArrayList<RequestAttachment>();
		int _total = 0;
		
		_requestAttachments = this.requestService.attachmentRetrieve(idRequest);
		
		Map<String,Object> _result = new HashMap<String,Object>(4);
		_result.put("data", _requestAttachments);
		_result.put("total", _total);
		_result.put("success", true);
		_result.put("message", "OK");
		return _result;
	}
	
	public void downloadHandler(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException{
		
		int idRequest = ServletRequestUtils.getRequiredIntParameter(request, "idRequest");
		Integer id = ServletRequestUtils.getIntParameter(request, "id");
		
		InputStream _inputStream = null;
		
		if (id != null){
			RequestAttachment _requestAttachment = this.requestService.attachmentRetrieve(idRequest, id);
			_inputStream = this.requestService.attachmentRetrieveStream(idRequest, id);
	        response.setContentType("binary/octet-stream");
	        response.setHeader("Content-Disposition", "attachment; filename=\"" + _requestAttachment.getName() + "\"");
		    try {FileCopyUtils.copy(_inputStream, response.getOutputStream());
			} catch (IOException e) {e.printStackTrace();}
		}
		else {
	        response.setContentType("application/zip");
	        response.setHeader("Content-Disposition", "attachment; filename=\"" + new SimpleDateFormat("yyyy_MM_dd").format(Calendar.getInstance().getTime()) + ".zip\"");
	        ZipOutputStream zipOutputStream = null;
			try {zipOutputStream = new ZipOutputStream(response.getOutputStream());
			} catch (IOException e1) {e1.printStackTrace();}
	        byte bytes[] = new byte[4096];
	        int bytesRead = 0;
	        BufferedInputStream _bufferedInputStream = null;
	        _inputStream = null;
		
			for (RequestAttachment _requestAttachment : this.requestService.attachmentRetrieve(idRequest)) {
				_inputStream = this.requestService.attachmentRetrieveStream(idRequest, _requestAttachment.getId());
				_bufferedInputStream = new BufferedInputStream(_inputStream);
	            try {
	            	zipOutputStream.putNextEntry(new ZipEntry(_requestAttachment.getName()));
		            bytesRead = 0;
		            while ((bytesRead = _bufferedInputStream.read(bytes)) != -1)
		            	zipOutputStream.write(bytes, 0, bytesRead);
		            zipOutputStream.closeEntry();
		            _bufferedInputStream.close();
		            _inputStream.close();
				} catch (IOException e) {e.printStackTrace();}
			}
			try {
				zipOutputStream.flush();
				zipOutputStream.finish();
			} catch (IOException e1) {e1.printStackTrace();}
		}
	}
	
	public void postHandler(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
		
		String idsDelete = ServletRequestUtils.getRequiredStringParameter(request, "idsDelete");
		int idRequest = ServletRequestUtils.getRequiredIntParameter(request, "idRequest");
		
		//borro los q me piden borrar
		for (String _idDelete : StringUtils.delimitedListToStringArray(idsDelete, StringArrayPropertyEditor.DEFAULT_SEPARATOR)) 
			this.requestService.attachmentDelete(idRequest,Integer.parseInt(_idDelete));
		
		//creo los nuevos
		InputStream _inputStream = null;
		MultiValueMap<String, MultipartFile> _fileParams = ((DefaultMultipartHttpServletRequest)request).getMultiFileMap();
		for (Map.Entry<String,List<MultipartFile>> _fileParam : _fileParams.entrySet())
			for (MultipartFile _file : _fileParam.getValue()){
				if (_file.getSize() != 0) { 
					try {_inputStream = _file.getInputStream();
					} catch (IOException e) {e.printStackTrace();}
					this.requestService.attachmentCreate(idRequest,_file.getOriginalFilename(),_inputStream);
				}
			}
		
		response.setContentType("text/html");
		try {response.getWriter().write("{\"success\":" + Boolean.toString(true) + "}");
		} catch (IOException e) {e.printStackTrace();}
	
	}
	
}
